<template>
  <div>

    <!--    头部查询区-->
    <!--    <el-card style="margin-bottom: 8px">-->
    <!--      <el-select placeholder="选择要显示的图片" @click.native="getImgs()" v-model="imgid" @change="selectChange">-->
    <!--        <el-option v-for="item in imgs" :key="item._id" :value="item._id" :label="item.filename"></el-option>-->
    <!--      </el-select>-->

    <!--        <el-button @click="dialogVisible=true">上传拓扑图</el-button>-->

    <!--    </el-card>-->

    <!--遮罩层-->
    <div class="loading" v-if="loading">
      <h4 class="tips">图片正在下载中...</h4>
      <!--进度条-->
      <el-progress type="circle" :percentage="progress" class="progress" :show-text="true"></el-progress>
    </div>

    <div style="margin-top: 20px;">
      <!--    <div v-loading.fullscreen.lock="loading" style="margin-top: 20px;">-->
      <div style="position: relative;top:40px;left:30px;width: 80px;z-index: 2" v-if="!noImgs">
        <el-dropdown trigger="click">
          <el-button type="success" plain>选择拓扑图<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="item in this.imgs" :key="item._id" @click.native="selectChange(item._id)">
              {{item.filename}}
            </el-dropdown-item>
            <el-dropdown-item icon="el-icon-s-tools" @click.native="dialogVisible=true">新增/删除拓扑
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>

      <!--    页面图片显示区-->
      <div style="z-index: 3;margin-top: -40px">
        <!--        <button type="button" @click="show">Click to show</button>-->
        <div class="images" v-viewer="{movable: true}">
          <img :src="url" alt="" @click="show" style="width: 100%">
        </div>


        <!--        <el-image-->
        <!--          v-show="!loading"-->
        <!--          :src="url"-->
        <!--        >-->

        <!--        </el-image>-->
      </div>


    </div>

    <!--    <el-dialog :visible.sync="dialogVisible">-->
    <!--      <img width="100%" :src="dialogImageUrl" alt="">-->
    <!--    </el-dialog> -->
    <!--    新增删除图片-->
    <el-dialog :visible.sync="dialogVisible">
<!--      下载进度条-->
        <el-progress v-if="videoFlag" :text-inside="true" :stroke-width="20" :percentage="videoUploadPercent"   ></el-progress>
      <el-upload
        :headers="headers"
        :data="imgPost"
        :before-upload="onBeforeUpload"
        :on-error="onError"
        :on-success="onSuccess"
        :on-progress="progressA"
        :http-request="fileupload"
        action="/api/tops"
        :file-list="imgs"
        list-type="picture-card">
        <i class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
<!--          <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent"  class="el-progress el-progress-custom"-->
<!--                       style="margin-top:10px;"></el-progress>-->
          <div class="el-progress el-progress-custom" v-if="file.percentage < 100">
                    <!--自定义进度条写在这里，你喜欢加啥都行，反正进度数字在下面๑乛◡乛๑-->
                    {{file.percentage | percent}}
                </div>
          <img class="el-upload-list__item-thumbnail" alt="">
          <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
          <i class="el-icon-view"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
          <span style="font-weight: bolder">{{file.filename}}</span>
        </div>

      </el-upload>
      <span>上传图片仅支持JPG格式，大小不能超过17M！</span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible1" @close="videoFlag=false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import 'viewerjs/dist/viewer.css'

  export default {
    middleware: 'metaTitle',
    meta: {title: '拓扑图'},
    name: "tops",

    created() {
      // Message({showClose: true, type: 'error', duration: 0, message: 'tops'});
      this.getDefaultImg();
    },
    data() {
      return {
        loading: true,
        progress: 0,
        videoFlag: false,
        uploadFile: "",
        videoUploadPercent: 0,
        noImgs: false,
        imgid: '',
        imgs: [],
        url: '',
        imgPost: {filename: ''},
        dialogImageUrl: '',
        dialogVisible: false,
        dialogVisible1: false,
        disabled: false,
        headers: {
          Authorization: 'Bearer ' + this.$store.state.user.token
        },
      }
    },
    watch: {},
    methods: {
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      async handleRemove(file) {
        let isTrue = await this.$confirm(`确定移除 ${file.filename}？`)
        if (isTrue) this.deleteImg(file._id)
      },
      async deleteImg(id) {
        try {
          const res = await this.$axios.delete('/api/tops/' + id);
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("删除成功")
            this.getImgs();
          }
        } catch (e) {
          this.$message.error('操作失败')
        }
      },
      async handlePictureCardPreview(file) {
        this.dialogImageUrl = await this.getTopImgUrl(file._id);
        this.dialogVisible1 = true;
      },
      onBeforeUpload(file) {
        //先检查上传文件是否合格
        const isJPG = file.type === 'image/jpeg';
        const isLt20M = file.size / 1024 / 1024 < 17;
        if (!isJPG) {
          this.$message.error('上传拓扑图只能是 JPG 格式!');
        }
        if (!isLt20M) {
          this.$message.error('上传拓扑图大小不能超过 17MB!');
        }
        this.imgPost.filename = file.name
        return isJPG && isLt20M;
      },


      async getDefaultImg() {
        await this.getImgs();
        if (this.imgs.length > 0) {
          this.getTopImg(this.imgs[0]._id)
        } else {
          this.noImgs = true
          this.loading = false
          this.$message("请先上传拓扑图")
          this.dialogVisible = true
        }

      },
      async getImgs() {
        const res = await this.$axios.get('/api/tops').catch((error) => {
            this.$message.error(error)
          }
        );
        if (res.status === 200 && res.data.code === "success") {
          this.imgs = res.data.result

        }
      },
      selectChange(id) {
        this.getTopImg(id)
      },
      async getTopImg(id) {
        const res = await this.$axios.get('/api/tops/' + id,
          {
            onDownloadProgress: progressEvent => {
              this.loading = true
              this.progress = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
              //  console.log(this.progress)
            }
          }
        ).catch((error) => {
            this.$message.error(error)
          }
        );
        try {

          if (!res.data.result.file.data) this.loading = false
          let bytes = new Uint8Array(res.data.result.file.data)
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          this.url = "data:image/png;base64," + window.btoa(storeData);
          this.progress = 0
          this.loading = false
        } catch (e) {
          console.log(e)
          this.$message.error("下载超时出错！")
          this.loading = false
        }

        //this.url = window.URL.createObjectURL(res.data.result[0].file.data)
      },
      //通过IMG_ID获取可以显示的URL
      async getTopImgUrl(id) {
        const res = await this.$axios.get('/api/tops/' + id, {
          onDownloadProgress: progressEvent => {
            this.videoFlag = true
            this.videoUploadPercent = Math.floor((progressEvent.loaded / progressEvent.total ) * 100);

            //  console.log(this.progress)
          }
        }).catch((error) => {
            this.$message.error(error)
          }
        );

        let bytes = new Uint8Array(res.data.result.file.data)
        let storeData = "";
        let len = bytes.byteLength;
        for (let i = 0; i < len; i++) {
          storeData += String.fromCharCode(bytes[i]);
        }
        return "data:image/png;base64," + window.btoa(storeData);

        //this.url = window.URL.createObjectURL(res.data.result[0].file.data)
      },
      onError(err, file, fileList) {
        this.$message.error(err)
      },
/**     文件正在上传时的钩子    **/
            progressA(event, file) {
              console.log("12312313131")
},
       fileupload(params) {
        const form = new FormData()
        form.append("file", params.file)
        form.append("filename", params.file.name)
        // form.append('fileSize',this.upfile.fileSize)
        this.$axios.post(params.action, form, {
          onUploadProgress:progressEvent=>{
            this.videoFlag = true
            this.videoUploadPercent = Math.floor((progressEvent.loaded / progressEvent.total ) * 100);
            // params.onProgress({percent: percent})
            params.onProgress({percent: this.videoUploadPercent})     //进度条
          }
        }).then(res => {
           if (this.videoUploadPercent === 100) {
            this.videoUploadPercent = 0
        }
          //处理成功情况
          this.videoFlag = false
          params.onSuccess(res.data)
        }).catch(e => {
          params.onError(e)
        })


      },
      onSuccess(reponse, file, fileList) {
        if (reponse.code === "ValidationError") {
          this.$message.error("上传失败，文件名已存在")
        }
        if (reponse.code === "success") {
          this.$message.success('上传成功')
          this.dialogVisible = false
          this.getImgs()
        }

        //刚上传的文件在fileList中的格式不对，需要重要整理
        // const Index = fileList.indexOf(file)
        // fileList[Index].id = file.response.id
        // fileList[Index].url = file.response.file

      },
      //下载图片
      async handleDownload(file) {
        // console.log(file);
        let res = await this.getTopImgUrl(file._id)
        this.videoFlag = false //关闭进度条
        this.videoUploadPercent = 0
        let blob = this.base64ToBlob(res)
        let aLink = document.createElement('a')
        let evt = document.createEvent("HTMLEvents")
        evt.initEvent("click", true, true)//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        aLink.download = file.filename;
        aLink.href = URL.createObjectURL(blob);
        aLink.click()
      },
//base64转blob
      base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
      },

      inited(viewer) {
        this.$viewer = viewer
      },
      show() {
        // this.$viewerApi({
        //   images: this.images,
        // })
        const viewer = this.$el.querySelector('.images').$viewer
        viewer.show()
      },
    },
  }
</script>

<style scoped>
  .loading {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: black;
    opacity: 0.8;
    z-index: 6;
  }

  .progress {
    /*width: 200px;*/
    /*height: 200px;*/
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -100px;
  }

  .tips {
    color: #409eff;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -90px;
    margin-top: -150px;
  }
   .el-upload-list--picture-card .el-progress-custom {
        width: 148px;
        height: 148px;
        line-height: 148px;
        text-align: center;
        color: #818181;
        background-color: rgba(0, 0, 0, .8);
    }
</style>
